const mysql = require('mysql2/promise');

// 数据库配置 - 与app.js保持一致
const dbConfig = {
  host: 'localhost',
  user: 'root',
  password: '123456',
  database: 'chatime',
  port: 3306
};

async function fixCommentCount() {
  let pool;
  
  try {
    console.log('🔧 开始修复评论数量...\n');
    
    // 连接数据库
    pool = mysql.createPool(dbConfig);
    console.log('✅ 数据库连接成功\n');
    
    // 1. 获取所有动态
    const [dynamics] = await pool.execute('SELECT id FROM dynamics');
    console.log(`📊 找到 ${dynamics.length} 条动态\n`);
    
    // 2. 为每个动态重新计算评论数量
    for (const dynamic of dynamics) {
      const dynamicId = dynamic.id;
      
      // 获取该动态的实际评论数量
      const [comments] = await pool.execute(
        'SELECT COUNT(*) as count FROM dynamic_comments WHERE dynamic_id = ?',
        [dynamicId]
      );
      
      const actualCount = comments[0].count;
      
      // 更新动态的评论数量
      await pool.execute(
        'UPDATE dynamics SET comment_count = ? WHERE id = ?',
        [actualCount, dynamicId]
      );
      
      console.log(`✅ 动态 ${dynamicId}: 评论数量已更新为 ${actualCount}`);
    }
    
    // 3. 验证修复结果
    console.log('\n🔍 验证修复结果...');
    const [verifyResult] = await pool.execute(`
      SELECT 
        d.id,
        d.comment_count as db_count,
        COUNT(c.id) as actual_count
      FROM dynamics d
      LEFT JOIN dynamic_comments c ON d.id = c.dynamic_id
      GROUP BY d.id, d.comment_count
      ORDER BY d.id
    `);
    
    console.log('\n📋 修复结果对比:');
    console.log('动态ID | 数据库计数 | 实际计数 | 状态');
    console.log('-------|------------|----------|------');
    
    let allCorrect = true;
    for (const row of verifyResult) {
      const status = row.db_count === row.actual_count ? '✅ 正确' : '❌ 错误';
      if (row.db_count !== row.actual_count) {
        allCorrect = false;
      }
      console.log(`${row.id} | ${row.db_count} | ${row.actual_count} | ${status}`);
    }
    
    if (allCorrect) {
      console.log('\n🎉 所有评论数量已修复完成！');
    } else {
      console.log('\n⚠️ 仍有部分数据需要修复');
    }
    
  } catch (error) {
    console.error('❌ 修复过程中出现错误:', error);
  } finally {
    if (pool) {
      await pool.end();
      console.log('\n🔌 数据库连接已关闭');
    }
  }
}

// 运行修复脚本
fixCommentCount(); 